﻿using System;
using System.Collections.Generic;
using System.Text;
using Csla;
using System.Data.Odbc;
using MinaspetroLibrary.Configuracoes;
using System.Data;
using Csla.Data;

namespace MinaspetroLibrary.FornecedorPack
{

    [Serializable()]
    public class FornecerdorSetorLigacao : BusinessBase<FornecerdorSetorLigacao>
    {
        #region Control Properties
        [Csla.NotUndoable()]
        private bool _isEmpty = false;

        public bool IsEmpty
        {
            get { return _isEmpty; }
        }
        #endregion

        #region Business Properties and Methods

        //declare members

        private Guid _idSetor = Guid.NewGuid();

        private Guid _idFornecedor = Guid.NewGuid();

        [System.ComponentModel.DataObjectField(true, true)]
        public Guid IdSetor
        {
            get
            {
                CanReadProperty("IdSetor", true);
                return _idSetor;
            }
            set
            {
                CanWriteProperty("IdSetor", true);
                if (value == null) value = Guid.Empty;
                if (!_idSetor.Equals(value))
                {
                    _idSetor = value;
                    PropertyHasChanged("IdSetor");
                }
            }
        }

        public Guid IdFornecedor
        {
            get
            {
                CanReadProperty("IdFornecedor", true);
                return _idFornecedor;
            }
            set
            {
                CanWriteProperty("IdFornecedor", true);
                if (value == null) value = Guid.Empty;
                if (!_idFornecedor.Equals(value))
                {
                    _idFornecedor = value;
                    PropertyHasChanged("IdFornecedor");
                }
            }
        }


        protected override object GetIdValue()
        {
            return _idFornecedor.ToString();
        }

        #endregion //Business Properties and Methods

        #region Validation Rules
        private void AddCustomRules()
        {
            //add custom/non-generated rules here...
        }

        private void AddCommonRules()
        {
        }

        protected override void AddBusinessRules()
        {
            AddCommonRules();
            AddCustomRules();
        }
        #endregion //Validation Rules

        #region Authorization Rules
        protected override void AddAuthorizationRules()
        {
        }


        public static bool CanGetObject()
        {
            return true;
        }

        public static bool CanAddObject()
        {
            return true;
        }

        public static bool CanEditObject()
        {
            return true;
        }

        public static bool CanDeleteObject()
        {
            return true;
        }
        #endregion //Authorization Rules

        #region Factory Methods
        private FornecerdorSetorLigacao()
        { /* require use of factory method */ }

        public static FornecerdorSetorLigacao NewFornecerdorSetorLigacao()
        {
            if (!CanAddObject())
                throw new System.Security.SecurityException("Usuário não autorizado a adicionar FornecerdorSetorLigacao");
            return DataPortal.Create<FornecerdorSetorLigacao>();
        }

        public static FornecerdorSetorLigacao GetFornecerdorSetorLigacao(Guid idFornecedor)
        {
            if (!CanGetObject())
                throw new System.Security.SecurityException("Usuário não autorizado a visualizar FornecerdorSetorLigacao");
            return DataPortal.Fetch<FornecerdorSetorLigacao>(new Criteria(idFornecedor));
        }

        public static FornecerdorSetorLigacao GetFornecerdorSetorLigacao(Guid idFornecedor, Guid idSetor)
        {
            if (!CanGetObject())
                throw new System.Security.SecurityException("Usuário não autorizado a visualizar FornecerdorSetorLigacao");
            return DataPortal.Fetch<FornecerdorSetorLigacao>(new Criteria(idFornecedor, idSetor));
        }

        public override FornecerdorSetorLigacao Save()
        {
            if (IsDeleted && !CanDeleteObject())
                throw new System.Security.SecurityException("Usuário não autorizado a remover FornecerdorSetorLigacao");
            else if (IsNew && !CanAddObject())
                throw new System.Security.SecurityException("Usuário não autorizado a adicionar FornecerdorSetorLigacao");
            else if (!CanEditObject())
                throw new System.Security.SecurityException("Usuário não autorizado a atualizar FornecerdorSetorLigacao");

            return base.Save();
        }

        public static void DeleteFornecerdorSetorLigacao(Guid idFornecedor)
        {
            if (!CanDeleteObject())
                throw new System.Security.SecurityException("Usuário não autorizado a remover FornecerdorSetorLigacao");
            DataPortal.Delete(new Criteria(idFornecedor));
        }

        public static void DeleteFornecerdorSetorLigacao(Guid idFornecedor, Guid idSetor)
        {
            if (!CanDeleteObject())
                throw new System.Security.SecurityException("Usuário não autorizado a remover FornecerdorSetorLigacao");
            DataPortal.Delete(new Criteria(idFornecedor, idSetor));
        }

        #endregion //Factory Methods

        #region Data Access

        #region Criteria

        [Serializable()]
        private class Criteria
        {
            public Guid IdFornecedor;
            public Guid IdSetor;

            public Criteria(Guid IdFornecedor)
            {
                this.IdFornecedor = IdFornecedor;
            }

            public Criteria(Guid IdFornecedor, Guid IdSetor)
            {
                this.IdFornecedor = IdFornecedor;
                this.IdSetor = IdSetor;
            }
        }

        #endregion //Criteria

        #region Data Access - Create
        [RunLocal]
        protected override void DataPortal_Create()
        {
            _isEmpty = false;
            ValidationRules.CheckRules();
        }

        #endregion //Data Access - Create

        #region Data Access - Fetch
        private void DataPortal_Fetch(Criteria criteria)
        {
            using (OdbcConnection cn = new OdbcConnection(ConfigDatabase.MinaspetroConnection))
            {
                cn.Open();
                ExecuteFetch(cn, criteria);
            }//using
        }

        private void ExecuteFetch(OdbcConnection cn, Criteria criteria)
        {
            using (OdbcCommand cm = cn.CreateCommand())
            {
                cm.CommandType = CommandType.Text;
                cm.CommandText = GetFetchScript(criteria);

                using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
                {
                    FetchObject(dr);
                    ValidationRules.CheckRules();
                    FetchChildren(dr);
                }
            }//using
        }

        private String GetFetchScript(Criteria criteria)
        {
            StringBuilder strQuery = new StringBuilder();
            strQuery.Append(" SELECT IdSetor, IdFornecedor FROM fornecedorsetorligacaotb WHERE 1=1 ");
            if (!criteria.IdSetor.Equals(Guid.Empty))
            {
                strQuery.Append(" AND IdSetor = '" + criteria.IdSetor.ToString() + "' ");
            }
            if (!criteria.IdFornecedor.Equals(Guid.Empty))
            {
                strQuery.Append(" AND IdFornecedor = '" + criteria.IdFornecedor.ToString() + "' ");
            }
            return strQuery.ToString();
        }

        private void FetchObject(SafeDataReader dr)
        {
            _isEmpty = !dr.Read();
            if (_isEmpty) return;
            _idSetor = new Guid(dr["IdSetor"].ToString());
            _idFornecedor = new Guid(dr["IdFornecedor"].ToString());
        }

        private void FetchChildren(SafeDataReader dr)
        {
        }
        #endregion //Data Access - Fetch

        #region Data Access - Insert
        protected override void DataPortal_Insert()
        {
            using (OdbcConnection cn = new OdbcConnection(ConfigDatabase.MinaspetroConnection))
            {
                cn.Open();
                ExecuteInsert(cn);
                //update child object(s)
                UpdateChildren(cn);
            }//using
            MinaspetroLibrary.UsuarioPack.Usuario.UsuarioInSession.AtualizarHitorico("Insert - FornecerdorSetorLigacaotb - Id: " + _idFornecedor.ToString());
        }

        private void ExecuteInsert(OdbcConnection cn)
        {
            using (OdbcCommand cm = cn.CreateCommand())
            {
                cm.CommandType = CommandType.Text;
                cm.CommandText = GetInsertScript();
                cm.ExecuteNonQuery();
            }//using
        }

        private string GetInsertScript()
        {
            return "INSERT INTO fornecedorsetorligacaotb(IdSetor, IdFornecedor) VALUES (\""
                + _idSetor.ToString() + "\", \"" + _idFornecedor.ToString() + "\")";
        }
        #endregion //Data Access - Insert

        #region Data Access - Update
        protected override void DataPortal_Update()
        {
            using (OdbcConnection cn = new OdbcConnection(ConfigDatabase.MinaspetroConnection))
            {
                cn.Open();
                if (base.IsDirty)
                {
                    ExecuteUpdate(cn);
                }
                //update child object(s)
                UpdateChildren(cn);
            }//using
            MinaspetroLibrary.UsuarioPack.Usuario.UsuarioInSession.AtualizarHitorico("Update - FornecerdorSetorLigacaotb - Id: " + _idFornecedor.ToString());
        }

        private void ExecuteUpdate(OdbcConnection cn)
        {
            using (OdbcCommand cm = cn.CreateCommand())
            {
                cm.CommandType = CommandType.Text;
                cm.CommandText = GetUpdateScript();
                if (cm.ExecuteNonQuery() == 0)
                    throw new Exception("Este registro foi editado por outro usuario.");
            }//using
        }

        private string GetUpdateScript()
        {
            return "Update fornecedorsetorligacaotb set "
                    + "IdSetor=\"" + _idSetor.ToString() + "\" "
                    + "WHERE IdFornecedor=\"" + _idFornecedor.ToString() + "\";";
        }

        private void UpdateChildren(OdbcConnection cn)
        {
        }
        #endregion //Data Access - Update

        #region Data Access - Delete
        protected override void DataPortal_DeleteSelf()
        {
            DataPortal_Delete(new Criteria(_idFornecedor));
        }

        private void DataPortal_Delete(Criteria criteria)
        {
            using (OdbcConnection cn = new OdbcConnection(ConfigDatabase.MinaspetroConnection))
            {
                cn.Open();
                ExecuteDelete(cn, criteria);
            }//using
            MinaspetroLibrary.UsuarioPack.Usuario.UsuarioInSession.AtualizarHitorico("Delete - FornecerdorSetorLigacaotb - Id: " + _idFornecedor.ToString());
        }

        private void ExecuteDelete(OdbcConnection cn, Criteria criteria)
        {
            using (OdbcCommand cm = cn.CreateCommand())
            {
                cm.CommandType = CommandType.Text;
                cm.CommandText = cm.CommandText = "DELETE from fornecedorsetorligacaotb WHERE IdFornecedor=\"" + criteria.IdFornecedor.ToString() + "\";";
                cm.ExecuteNonQuery();
            }//using
        }
        #endregion //Data Access - Delete
        #endregion //Data Access
    }
}
